package android.app.inflect;


import android.content.res.Resources;

/**
 * 反射或得资源id
 *
 */
public class Activity  extends android.app.show.Activity{
	/**
	 * 
	 * @param className  类名
	 * @param name  属性名
	 * @return
	 */
	public int getIdByName(String className, String name) {
		String packageName = this.getPackageName();
		Class<?> r = null;
		int id = 0;
		try {
			r = Class.forName(packageName + ".R");
			Class<?>[] classes = r.getClasses();
			Class<?> desireClass = null;
			for (int i = 0; i < classes.length; ++i) {
				if (classes[i].getName().split("\\$")[1].equals(className)) {
					desireClass = classes[i];
					break;
				}
			}
			if (desireClass != null) {
				id = desireClass.getField(name).getInt(desireClass);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		}
		return id;
	}
	public int R_id(String name){
		int id = getIdByContext("id", name);
		if(id > 0){
			return id;
		}
		return getIdByName("id", name);
	}

	public  int R_layout(String name){
		int id = getIdByContext("layout", name);
		if(id > 0){
			return id;
		}
		return getIdByName("layout", name);
	}

	public int R_drawable(String name){
		int id = getIdByContext("drawable", name);
		if(id > 0){
			return id;
		}
		id = getIdByName("drawable", name);
		if(id > 0){
			return id;
		}
		return -1;
	}

	private int getIdByContext(String className,
							   String name) {
		Resources res = null;
		int id = 0;
		try {
			res = getResources();
			id = res.getIdentifier(name, className, getPackageName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return id;
	}
}
